<?php


namespace App\Http\Controllers\Auth;


use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use App\Repositories\User\UserRepository;
use App\Contracts\Mobile\MobileCode;
use App\Http\Requests\CreateUser;
use App\Repositories\User\UserApi;

class RegisterController extends Controller {

	private $user;
	private $userApi;
	private $mobileCode;

	public function __construct(UserRepository $user, UserApi $userApi, MobileCode $mobileCode) {
		$this->middleware('guest',['except' => 'getCheckfield']);
		$this->user       = $user;
		$this->userApi    = $userApi;
		$this->mobileCode = $mobileCode;
	}

	public function getIndex() {
		return view('auth.register', [

		]);
	}

	public function postRegister(CreateUser $request) {

		$mobile      = $request->input('mobile');
		$mobile_code = $request->input('mobile_code');
		if (!$this->mobileCode->getCode($mobile) || $mobile_code != $this->mobileCode->getCode($mobile)) {
			error('验证码错误,请重新获取');
		}

		$user = $this->user->create($request->all());
		if($user){
			$this->userApi->loginById($user->id);
		}
		return redirect('/');
	}

	/**
	 * 发送手机验证码
	 */
	public function postMobilecode(Request $request) {

		$mobile = $request->input('mobile');

		$res = $this->mobileCode->send($mobile);

		success($res);
	}

	/**
	 * 验证 邮箱,手机号，昵称，手机验证码
	 * @param Request $request
	 */
	public function getCheckfield(Request $request) {

		$valid   = true;
		$message = '';

		if ($request->has('mobile') && $request->has('mobile_code')) {
			$mobile_code = $request->input('mobile_code');
			$mobile      = $request->input('mobile');
			if (!$this->mobileCode->getCode($mobile) || $mobile_code != $this->mobileCode->getCode($mobile)) {
				$valid   = false;
				$message = '验证码错误';
			}
		} elseif ($request->has('name')) {
			$name = $request->input('name');
			$data = $this->user->findBy('name', $name);
			if ($data) {
				$valid   = false;
				$message = '昵称已经被使用了，换一个吧';
			}

		} elseif ($request->has('email')) {
			$email = $request->input('email');
			$data  = $this->user->findBy('email', $email);
			if ($data) {
				$valid   = false;
				$message = '邮箱已经被使用了';
			}

		} elseif ($request->has('mobile')) {
			$mobile = $request->input('mobile');
			$data   = $this->user->findBy('mobile', $mobile);
			if ($data) {
				$valid   = false;
				$message = '手机号已经被注册了';
			}
		}

		echo json_encode(array(
			'valid'   => $valid,
			'message' => $message,
		));

	}


}
